package com.daisuxia.back.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.daisuxia.back.test.SerializeUtil;
import com.daisuxia.back.utils.JYTUtils;
import com.daisuxia.back.utils.PropertiesUtil;
import com.daisuxia.baofoo.BaofooAuthUtil;
import com.daisuxia.baofoo.XinyanAuthUtil;
import com.daisuxia.constant.LianLianConstant;
import com.daisuxia.lianlian.util.LLPayUtil;
import com.daisuxia.lianlian.util.RSAUtil;
import com.daisuxia.risk.service.IOutOrdersService;
import com.daisuxia.web.dao.IUserBankDao;
import com.daisuxia.web.pojo.OutOrders;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IInfoIndexService;
import com.daisuxia.web.service.IPushUserService;
import com.daisuxia.web.service.IUserBankService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.test.ThreadPool;
import com.daisuxia.web.util.*;

import redis.clients.jedis.JedisCluster;

@Service
@SuppressWarnings("all")
public class LianLianService implements ILianLianService {


	@Autowired
	private IUserBankService userBankService;

	@Autowired
	@Qualifier("userBankDaoImpl")
	private IUserBankDao userBankDao;

	@Autowired
	private IInfoIndexService infoIndexService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IPushUserService pushUserService;

	@Autowired
	private IBorrowOrderService borrowOrderService;

	@Autowired
	private IOutOrdersService outOrdersService;

	@Autowired
	JedisCluster jedisCluster;

	Logger logger = Logger.getLogger(getClass());

	/**
	 * 验证是否是本人银行卡
	 */
	public Map<String, Object> getBindCardToken(Map<String, String> tokenParaMap) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		String tranCode = PropertiesUtil.get("TRAN_CODE", PropertiesUtil.get("TRAN_CODE"));
		tokenParaMap.put("tranCode", tranCode);
		//金运通实名认证(四要素)
		retMap = JYTUtils.getInstance().JYTauth(tokenParaMap,logger);
		
		return retMap;
	}
	/**
	 * 验证是否是本人银行卡（不发短信）
	 */
	public Map<String, Object> getBindCardToken2(Map<String, String> tokenParaMap) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		String tranCode = PropertiesUtil.get("TRAN_CODE2", PropertiesUtil.get("TRAN_CODE2"));
		tokenParaMap.put("tranCode", tranCode);
		//金运通实名认证(四要素)
		retMap = JYTUtils.getInstance().JYTauth(tokenParaMap,logger);
		
		return retMap;
	}
	public Map<String, Object> bindCardValidate(Map<String, String> validateParaMap) {
		Map<String, Object> retMap = new HashMap<String, Object>();

		String token = validateParaMap.get("token");
		String userId = validateParaMap.get("userId");
		String verifyCode = validateParaMap.get("verifyCode");//验证码
		String cardNo = validateParaMap.get("cardNo");//银行卡
		String realName = validateParaMap.get("actName");//姓名
		String phone = validateParaMap.get("phone");//手机号
		String idNo = validateParaMap.get("idNo");//身份证件
		String bankId = validateParaMap.get("bankId");
		logger.error("tokenValidateS userId=" + userId);
		String no_agree = "默认签约号无";

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("oid_partner", LianLianConstant.getOidPartner());
		jsonMap.put("token", token);
		jsonMap.put("sign_type", "RSA");
		jsonMap.put("user_id", userId);
		jsonMap.put("verify_code", verifyCode);

		String sginOrigin = LLPayUtil.genSignDataByJavaObject(jsonMap);

		jsonMap.put("sign", RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));//RSAUtil.sign(LianLianConstant.getKey(), sginOrigin)

		String signParam = JSONUtil.beanToJson(jsonMap);
		logger.error("tokenValidateS userId=" + userId + " signParam:" + signParam);

		System.out.println("signParam:" + signParam);

		try {
			String tablelastName = DateUtil.getDateFormat(new Date(), "yyyyMMdd");
			String orderNo = GenerateNo.payRecordNo(userId);
			OutOrders outOrders = new OutOrders();
			outOrders.setUserId(userId);
			outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
			outOrders.setOrderNo(GenerateNo.nextOrdId());
			outOrders.setAct(OutOrders.ACT_VALIDATE_TOKEN);
			outOrders.setReqParams(signParam);
			outOrders.setTablelastName(tablelastName);
			outOrders.setOrderNo(orderNo);

			//获取流水号
			String trade_no = jedisCluster.get("XJX_TOKEN_USERID" + userId);

			if (trade_no == null | trade_no.equals("")) {
				retMap.put("code", "9999");
				retMap.put("msg", "信息过期,请重新发送验证码");
				return retMap;
			}

			Map result = XinyanAuthUtil.realAuth(
					trade_no,//流水单号
					verifyCode//验证码
			);

			/*Map ret = BaofooAuthUtil.simpleApi(
					cardNo,
					idNo,
					realName,
					phone,
					orderNo
			);*/
			//HttpUtil.getInstance().doPost("https://yintong.com.cn/traderapi/bankcardbindverfy.htm", signParam);
			logger.error("tokenValidateS userId=" + userId + " result:" + result);

			//Map<String,Object> retJsonMap  = JSONUtil.parseJSON2Map(ret);
			//返回码
			String retCodeSuccess = result.get("success")+"";
			String retCode = "0000";
			String retMsg;
			//第三方流水时间
			//Date time = new SimpleDateFormat("yyyyMMHHmmss").parse((String)ret.get("trade_date"));
			outOrders.setAddTime(new Date());

			if ("true".equals(retCodeSuccess)&&"0".equals(((Map)result.get("data")).get("code")+"")) {

				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put("userId", userId);
				params.put("limit", 1);

				List<UserCardInfo> userCardInfoList = userBankService.findUserCardByUserId(params);

				Map<String, String> bankInfo = userBankDao.selectByPrimaryKey(Integer.parseInt(bankId));

				if (null == userCardInfoList || userCardInfoList.isEmpty()) {
					UserCardInfo cardInfo = new UserCardInfo();
					cardInfo.setBank_id(Integer.parseInt(bankId));
					cardInfo.setCard_no(cardNo);
					cardInfo.setPhone(phone);
					cardInfo.setUserId(Integer.parseInt(userId));
					cardInfo.setOpenName(realName);
					cardInfo.setBankName(bankInfo.get("bankName") == null ? "" : bankInfo.get("bankName"));
					cardInfo.setStatus(UserCardInfo.STATUS_SUCCESS);
					cardInfo.setMainCard(UserCardInfo.MAINCARD_Z);
					cardInfo.setType(UserCardInfo.TYPE_DEBIT);
					cardInfo.setAgreeno(no_agree);
					cardInfo.setCreateTime(new Date());

					boolean flag = userBankDao.saveUserbankCard(cardInfo);

					System.out.println("bindCardValidate flag:" + flag);

					if (flag) {
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("userId", userId);
						this.infoIndexService.authBank(map);//设置状态-第一次绑卡
						//地推 绑卡
						ThreadPool pool = ThreadPool.getInstance();
						pool.execute(new DtThread(UserPushUntil.BANKAPPROVE, Integer.valueOf(userId), null, new Date(), userService, pushUserService, borrowOrderService, null));

						retMsg = "绑卡成功";
					} else {
						retCode = "9999";
						retMsg = "帐户银行信息保存失败";
					}

				} else {

					UserCardInfo cardInfoSave = new UserCardInfo();
					cardInfoSave.setBank_id(Integer.parseInt(bankId));
					cardInfoSave.setCard_no(cardNo);
					cardInfoSave.setPhone(phone);
					cardInfoSave.setUserId(Integer.parseInt(userId));
					cardInfoSave.setOpenName(realName);
					cardInfoSave.setBankName(bankInfo.get("bankName") == null ? "" : bankInfo.get("bankName"));
					cardInfoSave.setStatus(UserCardInfo.STATUS_SUCCESS);
					cardInfoSave.setMainCard(UserCardInfo.MAINCARD_Z);
					cardInfoSave.setType(UserCardInfo.TYPE_DEBIT);
					cardInfoSave.setAgreeno(no_agree);
					cardInfoSave.setUpdateTime(new Date());
					boolean flag = userBankService.updateUserBankCard(cardInfoSave);

					if (flag) {
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("userId", userId);
						this.infoIndexService.authBankOld(map);//设置状态---重新绑卡

						retMsg = "重新绑卡成功";
					} else {
						retCode = "9999";
						retMsg = "帐户银行信息保存失败";
					}
				}
				outOrders.setStatus(OutOrders.STATUS_SUC);
				logger.error("tokenValidateS userId=" + userId + " getToken success retCode:" + retCode);
			}
			else if ("true".equals(result.get("success")+"")
					&& !"0".equals(((Map)result.get("data")).get("code")+"")
					) {
				retMsg = ((Map)result.get("data")).get("org_desc")+"";
			}
			else if ("false".equals(retCodeSuccess)
					|| XinyanAuthUtil.errorList.contains(result.get("errorCode").toString())
					) {
				retMsg = result.get("errorMsg").toString();
				logger.info(" xinyan bindcard auth userId=" + userId + " result="+result);
			} else {
				retMsg = "绑卡功能错误，请联系客服";
				logger.error("tokenValidateS userId=" + userId + " error userId=" + userId + " result=" + result);
				outOrders.setStatus(OutOrders.STATUS_OTHER);
			}

			outOrders.setReturnParams(result.toString());
			
			//TODO songss 入库失败，暂时屏蔽掉。这个应该是一个记录表（每天生成一个这个表）
			//打开当前注释看看会不会报错
			outOrdersService.insertByTablelastName(outOrders);

			retMap.put("code", retCode);
			retMap.put("msg", retMsg);

		} catch (Exception e) {
			logger.error("tokenValidateS error userId=" + userId, e);
			retMap.put("code", "9999");
			retMap.put("msg", "系统繁忙 请稍候再试");
		}

		return retMap;
	}
	

	@Override
	public Map<String, Object> bindCard(String respCode, Map<String, String> validateParaMap) {
		if ("0000".equals(respCode)) {
			String userId = validateParaMap.get("userId");//用户id
			String bankId = validateParaMap.get("bankId");//
			String cardNo = validateParaMap.get("cardNo");//
			String phone = validateParaMap.get("phone");//手机号码
			String realName = validateParaMap.get("realName");//
			String no_agree = validateParaMap.get("no_agree");//
			
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("userId", userId);
			params.put("limit", 1);

			List<UserCardInfo> userCardInfoList = userBankService.findUserCardByUserId(params);

			Map<String, String> bankInfo = userBankDao.selectByPrimaryKey(Integer.parseInt(bankId));

			if (null == userCardInfoList || userCardInfoList.isEmpty()) {
				UserCardInfo cardInfo = new UserCardInfo();
				cardInfo.setBank_id(Integer.parseInt(bankId));
				cardInfo.setCard_no(cardNo);
				cardInfo.setPhone(phone);
				cardInfo.setUserId(Integer.parseInt(userId));
				cardInfo.setOpenName(realName);
				cardInfo.setBankName(bankInfo.get("bankName") == null ? "" : bankInfo.get("bankName"));
				cardInfo.setStatus(UserCardInfo.STATUS_SUCCESS);
				cardInfo.setMainCard(UserCardInfo.MAINCARD_Z);
				cardInfo.setType(UserCardInfo.TYPE_DEBIT);
				cardInfo.setAgreeno(no_agree);
				cardInfo.setCreateTime(new Date());

				boolean flag = userBankDao.saveUserbankCard(cardInfo);

				System.out.println("bindCardValidate flag:" + flag);

				if (flag) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("userId", userId);
					this.infoIndexService.authBank(map);//设置状态-第一次绑卡
					//地推 绑卡
					ThreadPool pool = ThreadPool.getInstance();
					pool.execute(new DtThread(UserPushUntil.BANKAPPROVE, Integer.valueOf(userId), null, new Date(), userService, pushUserService, borrowOrderService, null));
				}
			} else {
				UserCardInfo cardInfoSave = new UserCardInfo();
				cardInfoSave.setBank_id(Integer.parseInt(bankId));
				cardInfoSave.setCard_no(cardNo);
				cardInfoSave.setPhone(phone);
				cardInfoSave.setUserId(Integer.parseInt(userId));
				cardInfoSave.setOpenName(realName);
				cardInfoSave.setBankName(bankInfo.get("bankName") == null ? "" : bankInfo.get("bankName"));
				cardInfoSave.setStatus(UserCardInfo.STATUS_SUCCESS);
				cardInfoSave.setMainCard(UserCardInfo.MAINCARD_Z);
				cardInfoSave.setType(UserCardInfo.TYPE_DEBIT);
				cardInfoSave.setAgreeno(no_agree);
				cardInfoSave.setUpdateTime(new Date());
				boolean flag = userBankService.updateUserBankCard(cardInfoSave);

				if (flag) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("userId", userId);
					this.infoIndexService.authBankOld(map);//设置状态---重新绑卡
				}
			}
		}
	return null;
	}
}
